package com.jcxh.sg_exam.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcxh.sg_exam.pojo.Admin;
import com.jcxh.sg_exam.pojo.Result;
import com.jcxh.sg_exam.pojo.dto.AdminDto;
import com.jcxh.sg_exam.service.AdminService;
import com.jcxh.sg_exam.mapper.AdminMapper;
import com.jcxh.sg_exam.utils.BCrypt;
import com.jcxh.sg_exam.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lenovo
 * @description 针对表【admin】的数据库操作Service实现
 * @createDate 2024-08-06 14:27:43
 */
@Service
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
        implements AdminService {

    @Override
    public Result login(AdminDto adminDto) {
        if (adminDto == null || StringUtils.isBlank(adminDto.getUsername()) || StringUtils.isBlank(adminDto.getPassword())) {
            return Result.error("请输入账号密码进行登录");
        }

        Admin selectByUsername = lambdaQuery().eq(Admin::getUsername, adminDto.getUsername()).one();
        if (selectByUsername == null) {
            return Result.error("账号不存在");
        }

        boolean checkpw = BCrypt.checkpw(adminDto.getPassword(), selectByUsername.getPassword());
        if (!checkpw) {
            return Result.error("密码错误");
        }

        selectByUsername.setPassword("");
        Map<String, Object> map = new HashMap<>();
        map.put("adminUser", selectByUsername);
        String token = JwtUtils.generateJwt(map);
        // 不记录 token 到日志中
        //log.info("管理端id为{}的用户 登录生成了token", selectByUsername.getId());

        map.put("token", token);

        //log.info("{}",map);
        return Result.success(map);
    }

    @Override
    public Result register(AdminDto adminDto) {
        // 先检查 adminDto 是否为 null
        if (adminDto == null || StringUtils.isBlank(adminDto.getUsername()) || StringUtils.isBlank(adminDto.getPassword())) {
            return Result.error("请输入账号密码进行注册");
        }

        // 检查用户是否已存在
        Admin selectByUsername = lambdaQuery().eq(Admin::getUsername, adminDto.getUsername()).one();
        if (selectByUsername != null) {
            return Result.error("该账号已经存在，请重新注册");
        }

        // 用户不存在，创建新用户
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminDto, admin);
        admin.setCreateTime(new Date());

        // 处理密码加密
        String salt = BCrypt.gensalt(10);
        String hashedPassword = BCrypt.hashpw(admin.getPassword(), salt);
        admin.setPassword(hashedPassword);

        try {
            save(admin);
        } catch (Exception e) {
            // 捕获异常并返回错误信息
            log.error("管理员注册失败", e);
            return Result.error("注册失败，请稍后重试");
        }

        return Result.success("注册成功");
    }
}




